/**
 *
 */
package com.movitech.mobile.cz.base.common.util;

import com.movitech.mobile.cz.base.common.spring.SpringContextHolder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.context.MessageSource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
 *
 * @author ThinkGem
 * @version 2013-05-22
 */

@SuppressWarnings("restriction")
public class StringUtils extends org.apache.commons.lang3.StringUtils {

    private static final char SEPARATOR = '_';
    private static final String CHARSET_NAME = "UTF-8";

    public static String object2StringNotNull(Object o) {
        try {
            if (o == null) {
                return "";
            }
            return o.toString();
        } catch (Exception localException) {
        }
        return "";
    }

    public static boolean isNotEmpty(String str) {
        return object2StringNotNull(str).trim().length() > 0;
    }

    public static String enCodeString(String content) {
        if (StringUtils.isNotEmpty(content)) {
            try {
                content = URLEncoder.encode(content, "UTF-8");
            } catch (Exception e) {
            }
        }
        return content;
    }

    public static String deCodeString(String content) {
        if (StringUtils.isNotEmpty(content)) {
            try {
                content = URLDecoder.decode(content, "UTF-8");
            } catch (Exception e) {
                try {
                    if (content.lastIndexOf("%") != -1)
                        content = content.substring(0, content.lastIndexOf("%"));
                    content = URLDecoder.decode(content, "UTF-8");
                } catch (Exception e2) {
                }
            }
        }
        return content;
    }

    /**
     * 转换为字节数组
     *
     * @param str
     * @return
     */
    public static byte[] getBytes(String str) {
        if (str != null) {
            try {
                return str.getBytes(CHARSET_NAME);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 转换为字节数组
     *
     * @param bytes
     * @return
     */
    public static String toString(byte[] bytes) {
        try {
            return new String(bytes, CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            return EMPTY;
        }
    }

    /**
     * 是否包含字符串
     *
     * @param str  验证字符串
     * @param strs 字符串组
     * @return 包含返回true
     */
    public static boolean inString(String str, String... strs) {
        if (str != null) {
            for (String s : strs) {
                if (str.equals(trim(s))) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 替换掉HTML标签方法
     */
    public static String replaceHtml(String html) {
        if (isBlank(html)) {
            return "";
        }
        String regEx = "<.+?>";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(html);
        String s = m.replaceAll("");
        return s;
    }

    /**
     * 替换为手机识别的HTML，去掉样式及属性，保留回车。
     *
     * @param html
     * @return
     */
    public static String replaceMobileHtml(String html) {
        if (html == null) {
            return "";
        }
        return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>");
    }

    /**
     * 替换为手机识别的HTML，去掉样式及属性，保留回车。
     *
     * @param txt
     * @return
     */
    public static String toHtml(String txt) {
        if (txt == null) {
            return "";
        }
        return replace(replace(Encodes.escapeHtml(txt), "\n", "<br/>"), "\t", "&nbsp; &nbsp; ");
    }

    /**
     * 缩略字符串（不区分中英文字符）
     *
     * @param str    目标字符串
     * @param length 截取长度
     * @return
     */
    public static String abbr(String str, int length) {
        if (str == null) {
            return "";
        }
        try {
            StringBuilder sb = new StringBuilder();
            int currentLength = 0;
            for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
                currentLength += String.valueOf(c).getBytes("GBK").length;
                if (currentLength <= length - 3) {
                    sb.append(c);
                } else {
                    sb.append("...");
                    break;
                }
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String abbr2(String param, int length) {
        if (param == null) {
            return "";
        }
        StringBuffer result = new StringBuffer();
        int n = 0;
        char temp;
        boolean isCode = false; // 是不是HTML代码
        boolean isHTML = false; // 是不是HTML特殊字符,如&nbsp;
        for (int i = 0; i < param.length(); i++) {
            temp = param.charAt(i);
            if (temp == '<') {
                isCode = true;
            } else if (temp == '&') {
                isHTML = true;
            } else if (temp == '>' && isCode) {
                n = n - 1;
                isCode = false;
            } else if (temp == ';' && isHTML) {
                isHTML = false;
            }
            try {
                if (!isCode && !isHTML) {
                    n += String.valueOf(temp).getBytes("GBK").length;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            if (n <= length - 3) {
                result.append(temp);
            } else {
                result.append("...");
                break;
            }
        }
        // 取出截取字符串中的HTML标记
        String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)", "$1$2");
        // 去掉不需要结素标记的HTML标记
        temp_result = temp_result.replaceAll(
                "</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>",
                "");
        // 去掉成对的HTML标记
        temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>", "$2");
        // 用正则表达式取出标记
        Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
        Matcher m = p.matcher(temp_result);
        List<String> endHTML = new ArrayList<String>();
        while (m.find()) {
            endHTML.add(m.group(1));
        }
        // 补全不成对的HTML标记
        for (int i = endHTML.size() - 1; i >= 0; i--) {
            result.append("</");
            result.append(endHTML.get(i));
            result.append(">");
        }
        return result.toString();
    }

    /**
     * 转换为Double类型
     */
    public static Double toDouble(Object val) {
        if (val == null) {
            return 0D;
        }
        try {
            return Double.valueOf(trim(val.toString()));
        } catch (Exception e) {
            return 0D;
        }
    }

    /**
     * 转换为Float类型
     */
    public static Float toFloat(Object val) {
        return toDouble(val).floatValue();
    }

    /**
     * 转换为Long类型
     */
    public static Long toLong(Object val) {
        return toDouble(val).longValue();
    }

    /**
     * 转换为Integer类型
     */
    public static Integer toInteger(Object val) {
        return toLong(val).intValue();
    }

    /**
     * 获得i18n字符串
     */
    public static String getMessage(String code, Object[] args) {
        LocaleResolver localLocaleResolver = (LocaleResolver) SpringContextHolder.getBean(LocaleResolver.class);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Locale localLocale = localLocaleResolver.resolveLocale(request);
        return SpringContextHolder.getApplicationContext().getMessage(code, args, localLocale);
    }

    /**
     * 获得用户远程地址
     */
    public static String getRemoteAddr(HttpServletRequest request) {
        String ip = "";
        try {
            ip = request.getHeader("x-forwarded-for");
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            if (isNotEmpty(ip)) {
                ip = ip.split("\\,")[0].trim();
            }
        } catch (Exception e) {
        }
        return ip;
    }

    /**
     * 驼峰命名法工具
     *
     * @return toCamelCase("hello_world") == "helloWorld"
     * toCapitalizeCamelCase("hello_world") == "HelloWorld"
     * toUnderScoreCase("helloWorld") = "hello_world"
     */
    public static String toCamelCase(String s) {
        if (s == null) {
            return null;
        }

        s = s.toLowerCase();

        StringBuilder sb = new StringBuilder(s.length());
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c == SEPARATOR) {
                upperCase = true;
            } else if (upperCase) {
                sb.append(Character.toUpperCase(c));
                upperCase = false;
            } else {
                sb.append(c);
            }
        }

        return sb.toString();
    }

    /**
     * 驼峰命名法工具
     *
     * @return toCamelCase("hello_world") == "helloWorld"
     * toCapitalizeCamelCase("hello_world") == "HelloWorld"
     * toUnderScoreCase("helloWorld") = "hello_world"
     */
    public static String toCapitalizeCamelCase(String s) {
        if (s == null) {
            return null;
        }
        s = toCamelCase(s);
        return s.substring(0, 1).toUpperCase() + s.substring(1);
    }

    /**
     * 驼峰命名法工具
     *
     * @return toCamelCase("hello_world") == "helloWorld"
     * toCapitalizeCamelCase("hello_world") == "HelloWorld"
     * toUnderScoreCase("helloWorld") = "hello_world"
     */
    public static String toUnderScoreCase(String s) {
        if (s == null) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            boolean nextUpperCase = true;

            if (i < (s.length() - 1)) {
                nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
            }

            if ((i > 0) && Character.isUpperCase(c)) {
                if (!upperCase || !nextUpperCase) {
                    sb.append(SEPARATOR);
                }
                upperCase = true;
            } else {
                upperCase = false;
            }

            sb.append(Character.toLowerCase(c));
        }

        return sb.toString();
    }

    /**
     * 如果不为空，则设置值
     *
     * @param target
     * @param source
     */
    public static void setValueIfNotBlank(String target, String source) {
        if (isNotBlank(source)) {
            target = source;
        }
    }

    /**
     * 转换为JS获取对象值，生成三目运算返回结果
     *
     * @param objectString 对象串 例如：row.user.id
     *                     返回：!row?'':!row.user?'':!row.user.id?'':row.user.id
     */
    public static String jsGetVal(String objectString) {
        StringBuilder result = new StringBuilder();
        StringBuilder val = new StringBuilder();
        String[] vals = split(objectString, ".");
        for (int i = 0; i < vals.length; i++) {
            val.append("." + vals[i]);
            result.append("!" + (val.substring(1)) + "?'':");
        }
        result.append(val.substring(1));
        return result.toString();
    }

    /**
     * 随机获取n位数字
     *
     * @param n
     * @return
     */
    public static String getRandNum(int n) {
        char[] rand = new char[n];
        String str = "0123456789";
        for (int i = 0; i < n; i++) {
            Random rd = new Random();
            int index = rd.nextInt(str.length());
            rand[i] = str.charAt(index);
        }
        return new String(rand);
    }

    /**
     * 随机获取n位数字字母
     *
     * @param n
     * @return
     */
    public static String getRandNum2(int n) {
        char[] rand = new char[n];
        String str = "123456789qwertyuipkjhgfdsaxcvbnmQWERTYUIPLKJHGFDSAXCVBNM";
        for (int i = 0; i < n; i++) {
            Random rd = new Random();
            int index = rd.nextInt(str.length());
            rand[i] = str.charAt(index);
        }
        return new String(rand);
    }

    /**
     * 转数字
     *
     * @param obj
     * @return
     */
    public static int O2I(Object obj) {
        try {
            return Integer.valueOf(obj.toString());
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    /**
     * 字符串转换unicode
     */
    public static String string2Unicode(String string) {
        StringBuffer unicode = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);
            String s = Integer.toHexString(c);
            if (s.length() == 2) {
                s = "00" + s;
            }
            unicode.append(s);
        }
        return unicode.toString();
    }

    public static String getStringFromInputStream(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        try {
            InputStream is = request.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String s = "";
            while ((s = br.readLine()) != null) {
                sb.append(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static boolean hasLength(String journalKey) {
        if (journalKey == null) {
            return false;
        }
        if (journalKey.trim().length() == 0) {
            return false;
        }
        return true;
    }

    /**
     * list
     *
     * @param str
     * @return
     */
    public static List<String> string2List(String str, String add) {
        if (hasLength(str)) {
            String[] s = str.split(",");
            List<String> list = new ArrayList<String>();
            for (String string : s) {
                list.add(add + string);
            }
            return list;
        }
        return null;
    }

    public static boolean isEmpty(String str) {
        return str == null || (str != null && str.length() == 0);
    }

    public static String trim(String str) {
        if (isEmpty(str)) {
            return str;
        } else {
            return str.trim();
        }
    }

    // 加密
    public static String getBase64(String str) {
        byte[] b = null;
        String s = null;
        try {
            try {
                b = str.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (b != null) {
                s = new BASE64Encoder().encode(b);
            }
        } catch (Exception e) {
        }
        return s;
    }

    // 解密
    public static String getFromBase64(String s) {
        byte[] b = null;
        String result = null;
        try {
            if (s != null) {
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    b = decoder.decodeBuffer(s);
                    result = new String(b, "UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
        }
        return result;
    }

    public static String delHTMLTag(String htmlStr) {
        String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
        String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
        String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

        Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll(""); // 过滤script标签

        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll(""); // 过滤style标签

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); // 过滤html标签

        return htmlStr.trim(); // 返回文本字符串
    }

    /****
     * 获取当前的语言Local
     */
    public static Locale getLocal() {
        Locale locale = Locale.CHINA;
        CookieLocaleResolver cookieLocaleResolver = ((CookieLocaleResolver) SpringContextHolder.getBean("localeResolver"));
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes != null) {
            HttpServletRequest request = (servletRequestAttributes).getRequest();
            locale = cookieLocaleResolver.resolveLocale(request);
        }
        return locale;
    }

    /****
     * 根据code，获取message内容
     *
     * @param code
     * @param
     * @return
     */
    public static String getLocalMessage(String code) {
        return getLocalMessage(code, "");
    }

    /****
     * 根据code，获取message内容
     *
     * @param code
     * @return
     */
    public static String getLocalMessage(String code, String defaultMessage) {
        return getLocalMessage(code, defaultMessage, null);
    }

    /****
     * 根据code，获取message内容
     *
     * @param code
     * @param defaultMessage
     * @param args
     * @return
     */
    public static String getLocalMessage(String code, String defaultMessage, Object[] args) {
        MessageSource messageSource = (MessageSource) SpringContextHolder.getBean("messageSource");
        return messageSource.getMessage(code, args, getLocal());
    }

    /****
     * 去除BB/BC后的TW编号
     * @param codeNumber
     * @return
     */
    public static String getOrgicCnNumber(String codeNumber) {
        if (StringUtils.isNotEmpty(codeNumber) && codeNumber.length() > 2) {
            String subStr = codeNumber.substring(codeNumber.length() - 2);
            if (StringUtils.equalsIgnoreCase(subStr, "BB") || StringUtils.equalsIgnoreCase(subStr, "BC")) {
                codeNumber = codeNumber.substring(0, codeNumber.length() - 2);
            }
        }
        return codeNumber;
    }

    public static Integer convertNullToZero(Integer value) {
        if (value == null) {
            return 0;
        }
        return value;
    }
    
    public static List<String> getListBySplitStr(String str){
    	List<String> lstStr = new ArrayList<String>();
    	if(StringUtils.isNotEmpty(str)){
    		String[] arrStr = str.split("\\,");
    		for (int i = 0; i < arrStr.length; i++) {
				if(StringUtils.isNotEmpty(arrStr[i])){
					lstStr.add(arrStr[i]);
				}
			}
    	}
    	return lstStr;
    }


    public static boolean isListContainString(List<String> lstString ,String str){
        boolean isContain = false;
        if(CollectionUtils.isNotEmpty(lstString)){
            for (String item:lstString) {
                if(StringUtils.equalsIgnoreCase(item,str)){
                    isContain = true;
                    break;
                }
            }
        }
        return isContain;
    }
    
    public static String getListRemoves(String originStr,String removeStr){
    	String result = "";
    	if(StringUtils.isNotEmpty(originStr) && StringUtils.isNotEmpty(removeStr)){
    		List<String> lstOriginStrs = getListBySplitStr(originStr);
    		List<String> lstRemoveStrs = getListBySplitStr(removeStr);
    		for (String orgItem : lstOriginStrs) {
    			if(StringUtils.isNotEmpty(orgItem)){
    				boolean isExist = false;
    				for (String rmStr : lstRemoveStrs) {
    					if(StringUtils.equalsIgnoreCase(orgItem, rmStr)){
    						isExist = true;
							break;
    					}
					}
					if(isExist == false){
						if(StringUtils.isNotEmpty(result)) result += ",";
						result += orgItem;
					}
    			}
			}
    	}else{
    		if(StringUtils.isNotEmpty(originStr)){
				result = originStr;
    		}
    	}
    	return result;
    }

    public static String arr2String(Object[] arr){
        StringBuffer stringBuffer = new StringBuffer();
        for(int i = 0; i < arr.length;i++)
        {
            stringBuffer.append(arr[i]).append(",");
        }
        return  stringBuffer.substring(0,stringBuffer.length()-1).toString();
    }
    
    public static void main(String[] args) {
    	String currentTaskId = "";
    	String oldTaskIds = "";
    	String newTaskIds = "2,3,4";
//    	String taskIds = StringUtils.getListRemoves(oldTaskIds, currentTaskId);
//		System.out.println(taskIds);
//		taskIds = StringUtils.getListRemoves(newTaskIds, taskIds);
//		System.out.println(taskIds);
        System.out.println(arr2String(newTaskIds.split(",")));
	}

    /**
     * 格式化Double数据
     */
    public static String getFormatDouble(Double val,String pattern) {
        String result = "";
        if(val!=null){
            DecimalFormat decimalFormat = new DecimalFormat(pattern);
            result = decimalFormat.format(val);
        }
        return result;
    }
}
